package struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import service.BaseServiceI;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author zhangzhw 所有Action的基类，默认处理用户进程及错误
 */
public class BaseAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2537910421815160605L;
	protected final String SUCCESS="success";
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;
	ApplicationContext ctx;
	private BaseServiceI baseService;
	
	
	public BaseServiceI getBaseService() {
		return baseService;
	}

	public void setBaseService(BaseServiceI baseService) {
		this.baseService = baseService;
	}
	
	

	// 所有action 入口 处理 系统 登录和错误的问题
	public String execute() {
		// 处理系统问题
		try {
			// 未登录转入登录页面
			if (!login())
				if (!getUrl().equals("/SSH2/action/login.action"))
					return "login";

			// 执行请求操作
			return exe();
		} catch (Exception e) {
			e.printStackTrace();
			// 返回错误页面
			return "error";
		}
	}

	// 取得request对象
	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	// 取得response对象
	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	// 取得session对象
	public HttpSession getSession() {
		return getRequest().getSession();
	}

	// 判断登录
	public boolean login() {
		if (getSession().getAttribute("name") == null)
			return false;
		return true;
	}
	
	//取得 applicationContext对象
	public ApplicationContext getCtx()
	{
		return WebApplicationContextUtils.getRequiredWebApplicationContext(ServletActionContext.getServletContext()); 

	}
	
	//取得bean
	public Object getBean(String beanName)
	{
		return ctx.getBean(beanName);
	}

	public String getUrl() {
		String url = getRequest().getRequestURI();
		return url;
	}

	// 封装后的执行类 待覆盖
	public String exe() {
		return "success";
	}
	
	public static int str2int(String string)
	{
		if(string==null)
			return 0;
		else
			return Integer.valueOf(string);
	}

}
